package com.example.springbootwebconfig.config;

import com.example.springbootwebconfig.filter.DeptFilter;
import com.example.springbootwebconfig.listener.DeptListener;
import com.example.springbootwebconfig.servlet.DeptServlet;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.boot.web.servlet.ServletComponentScan;
import org.springframework.boot.web.servlet.ServletListenerRegistrationBean;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

/**
 * @author ljw
 * @description 增加自定义SpringBoot 配置
 * @date 2021/11/8 7:25
 */
@Configuration
//扫描本目录以及子目录带有的webservlet注解
@ServletComponentScan(basePackages={"com.example.springbootwebconfig"})
public class WebMvcConfig  implements WebMvcConfigurer {

    /**
     * 添加简单的 view 映射
     * @param
     * @author ljw
     * @date 2021/11/8 7:31
     */
    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
        registry.addViewController("/user").setViewName("user");
    }

    /**
     * 注册 Servlet
     * @param
     * @author ljw
     * @date 2021/11/12 7:53
     */
    @Bean
    public ServletRegistrationBean servletRegistrationBean() {
      return new ServletRegistrationBean(new DeptServlet(), "/dept/*");
    }

    /**
     * 注册 Filter
     * @param
     * @author ljw
     * @date 2021/11/12 7:53
     */
    @Bean
    public FilterRegistrationBean filterRegistrationBean() {
        FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean();
        filterRegistrationBean.setFilter(new DeptFilter());
        filterRegistrationBean.addUrlPatterns("/dept/*");
        //数值越小，越先执行
        filterRegistrationBean.setOrder(2);
        return filterRegistrationBean;
    }
    
    /**
     * 注册 Listener
     * @param 
     * @author ljw
     * @date 2021/11/16 7:55 
     */
    @Bean 
    public ServletListenerRegistrationBean<DeptListener> deptServletListenerRegistrationBean() {
        return new ServletListenerRegistrationBean<DeptListener>(new DeptListener());
    }
}
